package cn.iocoder.yudao.module.engine.service.core.filter.read.deprecated;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.engine.enums.EnumAudioType;
import cn.iocoder.yudao.module.engine.model.context.ControlEngineContext;
import cn.iocoder.yudao.module.engine.model.engine.EngineOutputData;
import cn.iocoder.yudao.module.engine.service.core.pipeline.FilterAdapter;
import cn.iocoder.yudao.module.engine.service.core.pipeline.FilterContext;
import cn.iocoder.yudao.module.engine.service.log.IEngineLogService;
import cn.iocoder.yudao.module.engine.util.AudioUtils;
import cn.iocoder.yudao.module.engine.util.EngineConvertUtils;
import cn.iocoder.yudao.module.resource.api.IAudioServiceApi;
import cn.iocoder.yudao.module.resource.api.IKeywordServiceApi;
import cn.iocoder.yudao.module.resource.api.enums.MessageSourceTypeEnum;
import cn.iocoder.yudao.module.resource.api.model.AudioDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 根据语音文本中的关键字回复音频
 */
@Slf4j
@Component("Keyword2AudioFilter")
@Deprecated
public class Keyword2AudioFilter extends FilterAdapter {
    @Resource
    private IKeywordServiceApi keywordApi;

    @Resource
    private IAudioServiceApi audioApi;

    @Resource
    private IEngineLogService logService;

    @Override
    public void read(FilterContext ctx, ControlEngineContext engineContext) throws Exception {
        final String userText = engineContext.getUserText();
        if (StrUtil.isEmpty(userText)) {
            ctx.fireRead(engineContext);
            return;
        }

        // 查询文本中包含的关键词
        final List<String> keywords = keywordApi.getKeywordListByText(userText);
        log.info("查询文本中包含的关键词: {}", keywords);
        if (CollUtil.isNotEmpty(keywords)) {
            logService.log(engineContext, "【关键词已命中】" + String.join(",", keywords));
        } else {
            logService.log(engineContext, "【关键词未命中】" + String.join(",", keywords));
        }

        if (CollUtil.isEmpty(keywords)) {
            ctx.fireRead(engineContext);
            return;
        }

        // 处理回复类型的对话
        final AudioDTO replyMainAudio = engineContext.getSynStatusCtx().getReplyMainAudio();
        if (replyMainAudio != null) {
            final EngineOutputData.Audio replyAudio = findReplyAudioByKeyword(engineContext, replyMainAudio, userText);
            log.info("回复音频: {}", JsonUtils.toJsonString(replyAudio));
            engineContext.getSynStatusCtx().setReplyMainAudio(null).syn();
            engineContext.getOutputData().setMainAudio(replyAudio);
            ctx.fireRead(engineContext);
            return;
        }

        // 通过关键词查询音频
        final List<AudioDTO> audios = audioApi.queryAudioByKeyword(engineContext.getRoleId(), keywords);
        log.info("通过关键词查询音频, keywords = {}, audios.size = {}, audios = {}",
                keywords, audios.size(), JsonUtils.toJsonString(audios));
        logService.log(engineContext, StrUtil.format("【通过关键词查询音频】音频数量{}个", audios.size()));

        if (CollUtil.isEmpty(audios)) {
            ctx.fireRead(engineContext);
            return;
        }

        // 如果触发了多个关键词，则随机一个
        final AudioDTO mainAudioDto = AudioUtils.randomAudio(engineContext.getSessionCtx(), audios);
        final EngineOutputData.Audio mainAudio = EngineConvertUtils.toEngineOutputData(engineContext.getUserText(), engineContext.getChatId(), MessageSourceTypeEnum.SYSTEM, EnumAudioType.CHAT, mainAudioDto);
        log.info("随机音频: {}", JsonUtils.toJsonString(mainAudio));
        logService.log(engineContext, StrUtil.format("【随机音频】[关键词]: {}, [内容]: {}",
                String.join(",", mainAudio.getKeywordNameList()), mainAudio.getAudioDesc()));

        final int relationType = mainAudio.getRelationType();
        if (relationType == AudioDTO.RELATION_TYPE_REPLY) {
            engineContext.getSynStatusCtx().setReplyMainAudio(mainAudioDto).syn();
            log.info("回复类型的对话，保存回复主音频, relationType = {}", relationType);
        }

        engineContext.getOutputData().setMainAudio(mainAudio);
        // 不执行后续filter
        //ctx.fireRead(engineContext);
    }

    private EngineOutputData.Audio findReplyAudioByKeyword(ControlEngineContext engineContext,
                                                           AudioDTO replyMainAudio, String userText) {
        final List<AudioDTO> replyAudios = new ArrayList<>();

        final AudioDTO.ReplyObjectDTO relationObject = (AudioDTO.ReplyObjectDTO) replyMainAudio.getRelationObject();
        final List<AudioDTO.ReplyItemDTO> replyItemList = relationObject.getReplyItemList();

        for (AudioDTO.ReplyItemDTO replyItem : replyItemList) {
            final List<String> keywordNameList = replyItem.getKeywordNameList();
            if (CollUtil.isNotEmpty(keywordNameList) && keywordNameList.contains(userText)) {
                replyAudios.add(replyItem.getReplyAudio());
                log.info("命中回复关键词, keyword = {}, audioId = {}", replyItem.getKeywordNameList(), replyItem.getReplyAudio().getAudioId());
            }
        }

        if (CollUtil.isEmpty(replyAudios)) {
            for (AudioDTO.ReplyItemDTO replyItem : replyItemList) {
                if (replyItem.isDefaultCondition()) {
                    replyAudios.add(replyItem.getReplyAudio());
                    log.info("命中回复默认值, audioId = {}", replyItem.getReplyAudio().getAudioId());
                }
            }
        }

        final EngineOutputData.Audio replyAudio = EngineConvertUtils.toEngineOutputData(
                engineContext.getUserText(), engineContext.getChatId(), MessageSourceTypeEnum.SYSTEM, EnumAudioType.CHAT,
                AudioUtils.randomAudio(engineContext.getSessionCtx(), replyAudios)
        );
        return replyAudio;
    }
}
